﻿using System.Data;
using System.Data.SQLite;
using System.Windows.Forms;


namespace GetContent
{
    class PhoneList
    {
        private static string _connectionString;

        public static void Initialize()
        {
            _connectionString = string.Format("Data Source={0}\\phones.s3db", Application.StartupPath);
        }


        public static int linkIsExists(string link)
        {
            try
            {
                var data = (DataTable)Query(string.Format("SELECT * FROM phones WHERE link ='{0}' ", link),1);//param = 1
                return data.Rows.Count;
            }
            catch (System.Exception ex)
            {
                return -1;
            }
        }
        public static object Query(string sql, int type = 0)//0 - bool, 1 - DataTable
        {
            var cnn = new SQLiteConnection(_connectionString);
            try
            {
                cnn.Open();
                var cmd = new SQLiteCommand(sql, cnn);

                if (type == 0)
                {
                    var rs  =  cmd.ExecuteNonQuery();
                    return rs;
                }
                else
                {
                    var dt = new DataTable();
                    var da = new SQLiteDataAdapter(sql, cnn);
                    da.Fill(dt);
                    return dt;
                }
            }
            catch //(System.Exception ex)
            {
                return null;
            }
            finally
            {
                if(cnn.State == ConnectionState.Open)
                    cnn.Close();
            }
        }

        public static void AddPhone(string link, string phone, string site = "raovat.com")
        {
            Query(string.Format("INSERT INTO phones VALUES ('{0}','{1}', '{2}')",link,phone, site));
        }

        //Số lần xuất hiện của 1 sđt cho 1 site
        public static int Count(string phone, string site = "raovat.com")
        {
            try
            {
                var data =
                    (DataTable)Query(string.Format("SELECT * FROM phones WHERE number LIKE '{0}' AND site LIKE '{1}'", phone, site), 1);//param = 1
                return data.Rows.Count;
            }
            catch
            {
                return -1;
            }
        }
    }
}
